package tsou.com.simple.realmtest;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;
import io.realm.RealmAsyncTask;
import io.realm.RealmResults;
import tsou.com.simple.realmtest.adapter.MyAdapter;
import tsou.com.simple.realmtest.bean.Student;
import tsou.com.simple.realmtest.bean.User;
import tsou.com.simple.realmtest.utils.UIUtils;

public class ProblemActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private ListView mListview;
    private List<String> titles = new ArrayList<>();
    private Realm mRealm;
    private RealmAsyncTask realmAsyncTask;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (realmAsyncTask != null && !realmAsyncTask.isCancelled()) {
            realmAsyncTask.cancel();
        }
        if (mRealm != null && !mRealm.isClosed()) {
            mRealm.close();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        mRealm = UIUtils.getRealmInstance();
        initData();
        initView();
        initListener();
    }

    private void initData() {
        titles.add("异步删除:先查找到数据（无效）");
        titles.add("deleteAll()（崩溃）");
        titles.add("delete(xxx.class)（崩溃）");
        titles.add("Intent：传递主键（重要官方建议）");
        titles.add("Intent：传递对象（崩溃）");
    }

    private void initView() {
        mListview = (ListView) findViewById(R.id.listview);

        mListview.setAdapter(new MyAdapter(this, titles));
    }

    private void initListener() {
        mListview.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        switch (position) {
            default:
                break;
            case 0://异步删除:先查找到数据
                //失败(原因是因为线程限制)
                final RealmResults<Student> students4 = mRealm.where(Student.class).findAll();
                realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        students4.deleteFromRealm(0);
                        students4.deleteFirstFromRealm();
                        students4.deleteLastFromRealm();
                        students4.deleteAllFromRealm();
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("删除成功");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        UIUtils.showToast("删除失败");
                    }
                });
                break;
            case 1://deleteAll(）
                //崩溃（原因是因为线程限制）
                mRealm.deleteAll();
                break;
            case 2://delete(xxx.class)
                //崩溃（原因是因为线程限制）
                mRealm.delete(Student.class);
                break;
            case 3://Intent：传递主键
                //你不可以直接通过 intent传递 RealmObject，建议你只传递RealmObject的标识符。

                RealmResults<User> all = mRealm.where(User.class).findAll();
                if (all.size() > 0) {
                    int id = all.get(0).getId();
                    Intent intent = new Intent(this, TestActivity.class);
                    intent.putExtra("id", id);
                    startActivity(intent);
                }else {
                    UIUtils.showToast("数据库没有数据");
                }

                break;
            case 4://Intent：传递对象
//                RealmResults<User> users = mRealm.where(User.class).findAll();
//                if (users.size() > 0) {
//                    User user = users.get(0);
//                    Intent intent = new Intent(this, TestActivity.class);
//                    intent.putExtra("user", user);
//                    startActivity(intent);
//                }else {
//                    UIUtils.showToast("数据库没有数据");
//                }
                break;
        }
    }
}
